<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ page import="java.util.List"%>
<%@ page import="javax.jdo.PersistenceManager"%>
<%@ page import="com.google.appengine.api.users.User"%>
<%@ page import="com.google.appengine.api.users.UserService"%>
<%@ page import="com.google.appengine.api.users.UserServiceFactory"%>
<%@ page import="au.org.htd.youslide.SongProject"%>
<%@ page import="au.org.htd.youslide.Background"%>
<%@ page import="au.org.htd.youslide.PMF"%>
<%@ page isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link href="styles/template.css" rel="stylesheet" type="text/css" />
<link href="styles/homepage.css" rel="stylesheet" type="text/css" />
<link href="styles/mavdialog.css" rel="stylesheet" type="text/css" />
<script src="scripts/mootools-1.2.2-core.js" type="text/javascript"></script>
<script src="scripts/mootools-1.2.2.2-more.js" type="text/javascript"></script>
<script src="scripts/util.js" type="text/javascript"></script>
<script src="scripts/clientcide.js" type="text/javascript"></script>
<script src="scripts/json2.js" type="text/javascript"></script>
<script src="scripts/audio-player.js" type="text/javascript"></script>
<script src="scripts/class.MavDialog.js" type="text/javascript"></script>
<script type="text/javascript">  
        AudioPlayer.setup("flash/player.swf", {
           transparentpagebg: "yes",
           width: 190
        });  
    </script>
<title>youslide - library</title>

<%
   UserService userService = UserServiceFactory.getUserService();
			User user = userService.getCurrentUser();
%>
<script type="text/javascript">
  var searchTags = '';
  var panelBoxId;
  var delayClickId;
  var a = 'domready';
  window.addEvent(a, function() {
    var library = $('library_main');

    function populateTags(obj, target) {
      var name = obj['name'];
      var count = obj['count'].toInt();
      var aTag = new Element('div', {
        'class':'tag',
        'text':name
      });
      if(target.id == 'allTags') {
        var weight = Math.log(count)/Math.log(51);
        var size = 8 + Math.round((20-8)*weight);
        aTag.setStyle('font-size',size+'pt');
        if(size < 10) {
          aTag.setStyles({
            'color':'#E79900',
            'font-weight':'bold'
          });
        } else if(size > 18) {
          aTag.setStyle('color','#FFCC66');
        }
      }
      aTag.addEvent('click', function() {
        aTag.setStyle('background-color','#4F5D66');
        if(searchTags=='') {
          searchTags = name;
        } else {
          if(searchTags.indexOf(name) >= 0) {
            searchTags = searchTags.replace(','+name,'')
                                   .replace(name+',','')
                                   .replace(name,'');
            aTag.setStyle('background-color','');
          } else {
            searchTags += (','+name);
          }         
        }
        if(searchTags!='') {
          new Request({
            method: 'get',
            url: '/search',
            data: { 'requestType':'byTags', 'tags':searchTags },
            onRequest: function() {
              delayClickId = panelBoxId; 
              killPanel();
              library.getChildren('.box').each(function(el) {
                library.removeChild(el);
              });
            },
            onComplete: function(response) {
              JSON.parse(response).forEach(insertSong, this);
            }
          }).send();
        }
      });
      aTag.inject(target);
      if(target.id == 'allTags') {
        new Element('span',{
          'class':'tagCount',
          'text':'('+count+')'
        }).inject(aTag);
      }
    }

    function getAllTags() {
      $('allTags').empty();
      new Request({
        method: 'get',
        url: '/search',
        data: { 'requestType':'listTags' },
        onComplete: function(response) {
          JSON.parse(response).forEach(function(el,i) {
            populateTags(el,$('allTags'));
          });
        }
      }).send();
    }

    function getSongTags(songId) {
      $('tags').empty();
      new Request({
        method: 'get',
        url: '/slides',
        data: { 'requestType':'getTags', 'songId':songId },
        onComplete: function(response) {
          JSON.parse(response).forEach(function(el,i) {
            populateTags(el,$('tags'));
          });
        }
      }).send();
    }

    function tagSong(songId, tag) {
      new Request({
        method: 'get',
        url: '/slides',
        data: { 'requestType':'addTag', 'songId':songId, 'tag':tag },
        onComplete: function(response) {
          getSongTags(songId);
        }
      }).send();
    }

    function killPanel() {
      var panel = $(panelBoxId+'panel');
      if(panel) { 
        panel.destroy();
        $(panelBoxId).setStyle('z-index',0);
      }
      panelBoxId = null;
    }

    disableSelection('#letters');
    disableSelection('.box');

    $('allTagsContainer').fade('out');
    
    var tagsSlideVar = new Fx.Slide($('tagsContainer'), {
      mode: 'horizontal', 
      transition: 'elastic:out',
      duration: '500'
    }).hide().show().hide();
  
    $('addTagButton').addEvent('click', function() {
      tagSong(panelBoxId, $('addTagText').value);
    });

    var tagPanelLink = new Element('div', {
      'class':'tagPanelLink'
    });
    tagPanelLink.inject($('letters'));
    tagPanelLink.addEvent('click', function(event) {
      getAllTags();
      $('allTagsContainer').fade('in');
    });

    var letterPanelLink = new Element('div', {
      'class':'letterPanelLink'
    });
    letterPanelLink.inject($('allTagsContainer'));
    letterPanelLink.addEvent('click', function(event) {
      $('allTagsContainer').fade('out');
    });
    
    var slideVar;
    if(Browser.Engine.trident) { //IE
      slideVar = new Fx.Slide($('lib_slidable'), {
        mode: 'vertical', 
        transition: 'sine:in', 
        duration: '500'
      }).hide().show().hide();
    } else {
      slideVar = new Fx.Slide($('lib_slidable'), {
        mode: 'horizontal', 
        transition: 'elastic:out',
        duration: '1500'
      }).hide().show().hide();
    }
    slideVar.slideIn();

    
    var y = 0; 
    $('scrollUp').addEvent('click', function(event){
      killPanel();
      y -= 300;
      if(y<0) y=0;
      new Fx.Scroll(library).start(0,y);
    });
  
    $('scrollDown').addEvent('click', function(event){
      killPanel();
      y += 300;
      var bottom = library.scrollHeight - library.getStyle('height').toInt();
      if(y>bottom) y = bottom;
      new Fx.Scroll(library).start(0,y);
    });
  
    library.addEvent('mousewheel', function(event){
      if (event.wheel > 0) {
        $('scrollUp').fireEvent('click');
      }
      else {
        $('scrollDown').fireEvent('click');
      }
    });
  
    $('goHome').addEvent('click', function(event){
      location.href='index.jsp';
    });
  
    function insertSong(obj, index) {
      var id = obj['id'];
      var bgId = obj['bgId'];
      var englishName = obj['englishName'];
      var chineseName = obj['chineseName'];
      var creator = obj['creator'];
      var when = obj['when'] + ' by';
      var audioUrl = obj['audioUrl'];
  
      var box = new Element('div', {
        'class':'box',
        'id':id
      }).inject('spacer','before');
  
      waiter = new Waiter(box, {
        containerProps: {
        styles: {
        position:'absolute',
        'text-align':'center'
      },
      'class':'waiterContainer'
      }
      });
      waiter.start(); 
      waiter.stop.delay(200, waiter);
  
      var bg = new Element('div').inject(box);
      if(bgId) {
        bg.setStyle('background',
            'url(/download?requestType=thumbnail&id='+bgId+') no-repeat');
      }
      new Element('span', {
        'html':englishName+'<br>'+chineseName
      }).inject(bg);
  
      var a = new Element('a', {
        'href':'#',
        'html':'<br>'+creator
      }).inject(new Element('span', {
        'text':''+when+' '
      }).inject(box));
  
      a.addEvent('click', function(){
        new Request({
          method: 'get',
          url: '/search',
          data: { 'requestType':'byCreator', 
          'creator':creator },
          onRequest: function() {
            library.getChildren('.box').each(function(el) {
              library.removeChild(el);
            });
          },
          onComplete: function(response) {
            $('search_count').set('text', 
                '('+JSON.parse(response).length+')');
            JSON.parse(response).forEach(insertSong, this);
          }
        }).send();
      });
  
      box.addEvent('click', function(){
        if(box.id == panelBoxId) { 
          killPanel();
          tagsSlideVar.slideOut();
          $('letters').fade('show');
          return;
        } 
        killPanel();
        if(needToScroll(box)) {
          new Fx.Scroll(library).toElement(box).chain(function() {
            y = box.parentNode.getScroll().y;
            displayPanel(box, audioUrl, creator);
          });
        } else {
          displayPanel(box, audioUrl, creator);
        }
      });
      if(box.id == delayClickId) {
        (function(){box.fireEvent('click');}).delay(1500); 
        delayClickId = null;
      }
    }
  
    function displayPanel(box, audioUrl, creator) {
      panel = new Element('div', {
        'class':'panel',
        'id':box.id+'panel'
      }).inject(box, 'before');
      panel.setStyles({
        'top':box.getPosition()['y']-5,
        'left':box.getPosition()['x']-5
      });
  
      var toolbar = new Element('div', {'class':'toolbar'});
      var rels = ['PPT in English and Chinses', 'PPT in Engilsh only',
                  'PPT in Chinese only', 'Lyrics PDF', 
                  'Edit this Song', 'Delete this Song']; 
      //'Attach other documents'];
      var links = ['/download?requestType=slides&id='+box.id,
                   '/download?requestType=englishSlides&id='+box.id,
                   '/download?requestType=chineseSlides&id='+box.id,
                   '/download?requestType=lyricsPdf&id='+box.id,
                   '/slides?requestType=edit&id='+box.id,
                   //'#',
                   '#'];        
      <%if (user != null) {%>
      if(creator == '<%=user.getNickname()%>') {
        var tool_ids = ['en_cn', 'en', 'cn', 'pdf', 'edt', 'del'];//, 'att'];
      } else if(creator == 'anonymous') {
        var tool_ids = ['edt'];
        rels = ['Edit this Song'];
        links = ['/slides?requestType=edit&id='+box.id];                       
      } else {
        rels = ['PPT in English and Chinses', 'PPT in Engilsh only',
                'PPT in Chinese only', 'Lyrics PDF', 
                'Edit this Song'];//, 'Attach other documents'];                      
        var tool_ids = ['en_cn', 'en', 'cn', 'pdf', 'edt'];//, 'att'];                  
      }
      <%}%>
  
      for(i=0; i<tool_ids.length; i++) {
        var link = new Element('div', {
          'id':tool_ids[i],
          'rel':rels[i],
          'onclick':'location.href="' +links[i]+ '"'
        }).inject(new Element('div', {
        }).inject(toolbar));
  
        if("del" == tool_ids[i]) {
          var letter = $('search_letter').value;
          link.addEvent('click', function(){
            new MavDialog({
              'title': 'Delete Song Project',
              'message': 'Are you sure you want to delete this project?',
              'cancelText':'No',
              'okText':'Yes',
              'force':true,
              'ok':function() {
              new Request({
                method: 'get',
                url: '/slides',
                data: { 'requestType':'delete', 
                'id':box.id,
                'letter':letter },
                onRequest: function() {
                  waiter = new Waiter(panel, {
                    containerProps: {
                    styles: {
                    position:'absolute',
                    'text-align':'center'
                  },
                  'class':'waiterContainer'
                  }
                  });
                  waiter.start(); 
                },
                onComplete: function(response) {
                  $(letter+'count').set('text', '('+response+')');
                  waiter.stop.delay(300, waiter);
                  killPanel();
                  (function(){ box.destroy(); }).delay(500);
                }
              }).send();                  
            }
            });
          });
        }
  
        if("att" == tool_ids[i]) {
          link.addEvent('click', function(){
            new MavDialog.Prompt({
              'title': 'Attach an Object',
              'message': 'Please enter URL',
              'force':true,
              'callback':function(url) {
              if(null == url) { return; }
              new Request({
                method: 'get',
                url: '/slides',
                data: { 'requestType':'attachObj', 
                'id':box.id,
                'url':url },
                onRequest: function() {
                  waiter = new Waiter(panel, {
                    containerProps: {
                    styles: {
                    position:'absolute',
                    'text-align':'center'
                  },
                  'class':'waiterContainer'
                  }
                  });
                  waiter.start(); 
                },
                onComplete: function(response) {
                  if(response.length>2) {
                    new MavDialog.Alert({
                      'title': 'Error attaching object',
                      'message': 'There was an error attaching:<br>' + url,
                      'width': 'auto',
                      'force': true
                    });
                  }
                  waiter.stop.delay(100, waiter);
                }
              }).send();       
            }
            });
          });
        }
      }
      toolbar.inject(panel);
      new Tips.Pointy($$('.panel .toolbar div div'), {
        pointyTipOptions: {
          point:9,
          width:100,
          pointyOptions: {
            theme:'light',
            closeButton:false
          }
        }
      });
  
      new Request({
        method: 'get',
        url: '/slides',
        data: { 'requestType':'getTags', 
        'songId':box.id },
        onComplete: function(response) {
          var songTags = JSON.parse(response);
          if(songTags.length > 0) {
//            new Element('div', {
//              'class':'tagLink',
//              'id':box.id+'tags'
//            }).inject(panel);
            getSongTags(box.id);
            searchTags = '';
          }
          $('allTagsContainer').fade('out');
          $('letters').fade('out');
          tagsSlideVar.slideIn();
        }
      }).send();
  
      var wrapper = new Element('div', {
        'class':'playerObj',
        'id':box.id+'player'
      });
  
      wrapper.inject(panel);
  
      var tools = new Element('div', {
        'class':'music_tools'
      });
      var attach = new Element('div', {
        'id':'link_button',
        'rel':'Link a song'
      });
      attach.addEvent('click', function(){
        new MavDialog.Prompt({
          'title': 'Attach a Song Link',
          'message': 'Please enter URL',
          'force':true,
          'callback':function(url) {
          if(null == url) { return }
          new Request({
            method: 'get',
            url: '/slides',
            data: { 'requestType':'attachAudio', 
            'id':box.id,
            'url':url },
            onRequest: function() {
              waiter = new Waiter(panel, {
                containerProps: {
                styles: {
                position:'absolute',
                'text-align':'center'
              },
              'class':'waiterContainer'
              }
              });
              waiter.start(); 
            },
            onComplete: function(response) {
              killPanel();
              (function() {displayPanel(box, response, creator);}).delay(300);
              waiter.stop.delay(300, waiter);
            }
          }).send();
        }
        });
      });
      attach.inject(tools);
      tools.inject(panel);
  
      if(null != audioUrl) {
        new Element('div', {id:box.id+'container'}).inject(wrapper);
        AudioPlayer.embed(box.id+'container', {soundFile: audioUrl});
  
        var del = new Element('div', {
          'id':'delete_button',
          'rel':'Delete audio link'
        });
        del.addEvent('click', function(){
          new MavDialog({
            'title': 'Delete audio link',
            'message': 'Are you sure you want to delete this link?',
            'cancelText':'No',
            'okText':'Yes',
            'force':true,
            'ok':function() {
            new Request({
              method: 'get',
              url: '/slides',
              data: { 'requestType':'removeAudio', 
              'id':box.id},
              onRequest: function() {
                waiter = new Waiter(panel, {
                  containerProps: {
                  styles: {
                  position:'absolute',
                  'text-align':'center'
                },
                'class':'waiterContainer'
                }
                });
                waiter.start(); 
              },
              onComplete: function(response) {
                $(box.id+'container').destroy();
                del.destroy();
                waiter.stop.delay(300, waiter);
              }
            }).send();
          }
          });
        });
        del.inject(tools);
      }
  
      new Tips.Pointy($$('.music_tools div'), {
        pointyTipOptions: {
        point:12,
        width:100,
        pointyOptions: {
        theme:'light',
        closeButton:false
      }
      }
      });
  
      box.setStyle('z-index','20');
      panelBoxId = box.id;          
    }
  
    $$('.letter_wrapper').addEvent('click', function(){
      killPanel();
      var search_letter = $('search_letter');
      if(this.id != search_letter.value) { 
        this.setStyles({'font-weight':'bold',
          'color':'white'});
        if(search_letter.value) {        
          $(search_letter.value).setStyles({'font-weight':'',
            'color':'#382615'});
        }
        search_letter.value = this.id;
      }
  
      new Request({
        method: 'get',
        url: '/search',
        data: { 'requestType':'byLetter', 'search_letter':this.id },
        onRequest: function() {
          library.getChildren('.box').each(function(el) {
            library.removeChild(el);
          });
        },
        onComplete: function(response) {
          JSON.parse(response).forEach(insertSong, this);
        }
      }).send();
    });
  
    $('search_button').addEvent('click', function() {
      if($('song_search').value.length < 2) {
        new MavDialog.Alert({
          'title': 'Song Search',
          'message': 'Please make sure your search term is at least 2 chrarcters long'
        });
        return;
      }
  
      killPanel();
      new Request({
        method: 'get',
        url: '/search',
        data: { 'requestType':'byContent', 
        'search_string':$('song_search').value},
        onRequest: function() {
          library.getChildren('.box').each(function(el) {
            library.removeChild(el);
          });
        },
        onComplete: function(response) {
          $('search_count').set('text', 
              '('+JSON.parse(response).length+')');
          JSON.parse(response).forEach(insertSong, this);
        }
      }).send();        
    });
  
    $('song_search').addEvent('keypress', function() {
      if(isEnterKey(event)) {
        $('search_button').fireEvent('click'); 
        return false;
      }
    });
  
    <c:if test="${empty sessionScope.letter}">
    $('A').fireEvent('click');
    </c:if>
    <c:if test="${not empty sessionScope.letter}">
    delayClickId = '<%=session.getAttribute("id")%>';
    $('<%=session.getAttribute("letter")%>').fireEvent('click');
    </c:if>
  });
</script>
</head>

<body>
<div id="masthead"><a href="index.jsp" id="branding"> <img
  src="images/logo.jpg" alt="youslide" border="0" /> </a> <%
    if (user != null) {
 %>
<div id='welcome'>Welcome, <%=user.getNickname()%> (<a
  href="<%=userService.createLogoutURL(request.getRequestURI())%>">Sign out</a>)</div>
<%
   } else {
%> <script type="text/javascript">location.href='index.jsp'</script> <%
    }
 %>
</div>
<div id="letters">
<%
   for (int letter = (int) 'A'; letter < (int) 'Z'; letter += 3) {
				char l1 = (char) letter;
				char l2 = (char) (letter + 1);
				char l3 = (char) (letter + 2);
				int len1 = SongProject.searchByLetter("" + l1).length();
				int len2 = SongProject.searchByLetter("" + l2).length();
				int len3 = 0;
				if (letter <= (int) 'X') {
					len3 = SongProject.searchByLetter("" + l3).length();
				} else {
					len3 = SongProject.searchByNumbers().length();
				}
%>
<div class='letter_wrapper' id='<%=l1%>'>
<div><%=l1%></div>
<div class='count_wrapper' id='<%=l1%>count'>(<%=len1%>)</div>
</div>
<div class='letter_wrapper' id='<%=l2%>'>
<div><%=l2%></div>
<div class='count_wrapper' id='<%=l2%>count'>(<%=len2%>)</div>
</div>
<%
   if (letter <= (int) 'X') {
%>
<div class='letter_wrapper' id='<%=l3%>'>
<div><%=l3%></div>
<div class='count_wrapper' id='<%=l3%>count'>(<%=len3%>)</div>
</div>
<%
   } else {
%>
<div class='letter_wrapper' id='0-9'>
<div>0-9</div>
<div class='count_wrapper' id='<%=l3%>count'>(<%=len3%>)</div>
</div>
<%
   }
			}
%> <input type="text" id="song_search" name="search_string" />
<form id='search_form' method='get' action='search'><input
  name='requestType' type='hidden' value='byContent' /> <img id="search_button"
  src='/images/search.png' width='20px' height='20px' />
<div class='count_wrapper' id='search_count'></div>
</form>
<form id='letters_form' method='get' action='search'><input
  name='search_letter' type='hidden' id='search_letter' /></form>
</div>
<div id="allTagsContainer">
<div id="allTags"></div>
</div>

<div id="tagsContainer">
<div id="tagTitle">Song tags:</div>
<div id="tags"></div>
<input id="addTagText" type="text" /><input id="addTagButton" type="button" value="Add"/>
</div>
<div id='goHome'></div>
<div id="wrapper" class="funbg">
<div id="lib_slidable">

<div style="float: left">
<h1>Library</h1>
</div>
<div id='scrollUp'></div>
<div id='scrollDown'></div>
<div id="library_main">
<div id='spacer'></div>
</div>
</div>
</div>
</body>
</html>